﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFMVVMDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static MainViewModel mainViewModel;// = new MainViewModel();
        private Timer timer;
        private readonly SynchronizationContext _Context;//获取线程的同步上下文
        public MainWindow()
        {
            //向单例中保存线程的同步上下文
            ViewModelHelper.Instance().Context = SynchronizationContext.Current;
            _Context = SynchronizationContext.Current;
            InitializeComponent();
            //new Test();
            test();
            //this.DataContext = mainViewModel;
            //如果在xaml中绑定DataContext，则需要在这里指定数据源
            //ViewModel只能创建一个，所有的View和逻辑代码只能调用一个ViewModel
            mainViewModel = DataContext as MainViewModel;
        }
        public void test()
        {
            int i = 0;
            //线程的同步上下文最好放在需要更新的UI的线程中，防止出现问题 <= 这里的子线程可以直接更新UI线程（不解）
            timer = new System.Threading.Timer(x =>
            {
                //https://www.cnblogs.com/zodiac444/p/7878358.html
                //https://blog.csdn.net/cgabriel/article/details/38371283
                //Post更新2
                //_Context?.Post(y =>
                //{
                //    i++;
                //    mainViewModel.Name = $"testName_{i}";
                //    mainViewModel.Pwd = $"testPwd_{i}";
                //}, null);

                //第三种方式来更新界面
                Dispatcher.Invoke(() =>
                {
                    i++;
                    mainViewModel.Name = $"testName_{i}";
                    mainViewModel.Pwd = $"testPwd_{i}";
                });
            }, null, 0, 1000);
        }
    }
}
